package org.skydiveapphd;

import org.skydiveapplibrary.R;
import org.skydiveapphd.interfaces.NotesNotifier;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

public class NotesEditActivity extends Fragment
{
	// listeners
	private OnClickListener saveListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			save();
		}
	};
	private OnClickListener cancelListener = new OnClickListener()
	{
		@Override
		public void onClick(View view)
		{
			getFragmentManager().popBackStack();
		}
	};
	
	public static NotesEditActivity newInstance(Bundle args) 
	{
		NotesEditActivity f = new NotesEditActivity();
		f.setArguments(args);
		return f;
	}
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    		Bundle savedInstanceState)
	{
	    	// Inflate the layout for this fragment
	    	return inflater.inflate(R.layout.notes_view, container, false);
	}
	
	@Override
	public void onResume()
	{
		super.onResume();
		initializeUI();
	}
		
	private void initializeUI()
	{
		// set header text
		TextView headerTextView = (TextView) getActivity().findViewById(R.id.EditHeaderTextView);
		headerTextView.setText(R.string.notes_editor_notes_label);

		// set notes
		String notes = (getArguments().containsKey(Constants.EXTRA_NOTES) ? getArguments().getString(Constants.EXTRA_NOTES) : "");
		EditText nField = (EditText) getActivity().findViewById(R.id.NotesField);
		nField.setText(notes);
		
		// add button listeners
		ImageButton saveButton = (ImageButton) getActivity().findViewById(R.id.NoteSaveButton);
		saveButton.setOnClickListener(saveListener);
		
		ImageButton cancelButton = (ImageButton) getActivity().findViewById(R.id.NoteCancelButton);
		cancelButton.setOnClickListener(cancelListener);
	}
	
	private void save()
	{
		// get notes
		EditText nField = (EditText) getActivity().findViewById(R.id.NotesField);
		String notes = nField.getText().toString();

		NotesNotifier f = (NotesNotifier) getFragmentManager().findFragmentByTag(getArguments().getString(Constants.EXTRA_FRAG_TAG));
		f.updateNotes(notes);
		getFragmentManager().popBackStack();
	}	
}
